package com.showcai.controller.groupPay;

import com.github.pagehelper.PageInfo;
import com.showcai.controller.base.BaseController;
import com.showcai.def.Constant;
import com.showcai.module.ApplyWatch;
import com.showcai.module.Order;
import com.showcai.module.Payment;
import com.showcai.module.User;
import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.result.ResultObj;
import com.showcai.result.ReturnCode;
import com.showcai.service.*;
import com.showcai.tools.json.JsonHandler;
import com.showcai.util.ExcelIn;
import com.showcai.util.ExcelOut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Baggio on 2018-9-6.
 */
@RequestMapping("/groupPay")
@Controller
public class GroupPayController extends BaseController {
private static  final  Long PRODUCT_ENTITY_ID_399=1514267657851015l;
    @Autowired
    OrderService orderService;
    @Autowired
    PaymentService paymentService;
    @Autowired
    ExpressInfoService expressInfoService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    ProductEntityService productEntityService;
    @Autowired
    ApplyService applyWatchService;

    @RequestMapping(value = "/groupPayList")
    public ModelAndView groupPay(Integer page,Integer pageSize) {
        ModelAndView mov = new ModelAndView();
        if (page == null || page == 0) {
            page = Constant.PAGENUM;
        }
        // 设置每页记录数
        if (pageSize == null || pageSize == 0) {
            pageSize = Constant.PAGESIZENum;
        }
        Map map = new HashMap<String, String>();
        map.put("page", String.valueOf(page));
        map.put("pageSize", String.valueOf(pageSize));
        map.put("payMode",Payment.PAY_MODE_GROUPPAY_BY_QXPC);
        PageInfo<Order> list = orderService.groupPayList(map);
        mov.addObject("pageInfo", list);
        mov.setViewName("groupPay/groupPayList");
        return mov;
    }
    /**
     * 导出Excel
     * @return
     */
    @RequestMapping(value = "/groupPayExcelOut")
    @ResponseBody
    public void excelOut() {
        Map<String, String> map = super.showRequestParameters();
        String[] strList = {"姓名", "电话", "产品Id", "收货地址"};
        String fileName = "newGroupPay" + new SimpleDateFormat("yyyyMMdd").format(new Date());
        List<LinkedList<String>> list = new ArrayList<>();

        ExcelOut.excelOut(fileName, response, strList, list);
    }
    /**
     * 导入Excel
     * @return
     */
    @RequestMapping(value = "/groupPayExcelIn")
    @ResponseBody
    public String excelIn(@RequestParam(value = "file", required = false) MultipartFile file) {
        ResultObj resultObj = new ResultObj();
        String[] strList = {"姓名", "电话", "产品Id", "收货地址"};
        List<HashMap<Integer, String>> list = ExcelIn.excelIn(strList,file);
        logger.info("import users===>>>>"+list.size());
        try {
            for (HashMap<Integer,String> map: list) {
                String userName = map.get(0);
                String phone =  map.get(1);
                String productEntityIdStr =  map.get(2);
                String address = map.get(3);
                ApplyWatch applyWatch = new ApplyWatch();
                User user = super.checkUser(phone, userName);
                applyWatch.setUserId(user.getTid());

                List<Long> productEntityIdList = new ArrayList<>();
                if (productEntityService.getProductEntityById(Long.valueOf(productEntityIdStr)) == null) {
                    throw new MyRunTimeExcption("没有找到产品颜色实体！");
                }

                productEntityIdList.add(Long.valueOf((String) map.get(2)));
                productEntityIdList.add(PRODUCT_ENTITY_ID_399);
                Order order = orderService.createOrder(productEntityIdList, user.getTid(), null, Order.ORDER_SOURCE_IMPORT);
                applyWatch.setOrderId(order.getOrderId());
                applyWatch.setName(userName);
                applyWatch.setPhone(phone);
                applyWatch.setAddress(address);
                applyWatchService.apply(applyWatch);
                List<Payment> paymentList = new ArrayList<>();
                Payment payment = new Payment();
                payment.setOrderId(order.getOrderId());
                payment.setPayMode(Payment.PAY_MODE_GROUPPAY_BY_QXPC);
                payment.setPrice(order.getOrderPrice());
                payment.setPayType(Payment.PAY_TYPE_PAY);
                payment.setStatus(Payment.STATUS_VALID);
                paymentList.add(payment);

                String paymentJSON = JsonHandler.toJSONArrayList(paymentList).toString();
                logger.info(paymentJSON);
                orderService.toPay(order.getOrderId(), paymentJSON);
            }
        } catch (MyRunTimeExcption myRunTimeExcption) {
            myRunTimeExcption.printStackTrace();
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(myRunTimeExcption.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(e.getMessage());
        }
            return resultObj.toJson();
    }
}
